<template>
  <div class="resource-analysis">
    <!-- 顶部筛选区 -->
    <Card class="filter-card">
      <div slot="title" class="card-title">
        <Icon type="md-analytics" />
        <span>资源分析</span>
      </div>
      <Row :gutter="16" type="flex" align="middle">
        <Col span="6">
          <DatePicker 
            type="daterange" 
            placeholder="选择日期范围"
            style="width: 100%"
            v-model="dateRange"
            @on-change="handleDateChange"
            :options="dateOptions"
          />
        </Col>
        <Col span="6">
          <Select 
            v-model="selectedDepartment"
            placeholder="选择科室"
            clearable
            style="width: 100%"
            @on-change="handleDepartmentChange"
          >
            <Option v-for="dept in departments" :key="dept.id" :value="dept.id">
              {{ dept.name }}
            </Option>
          </Select>
        </Col>
        <Col span="6">
          <Select 
            v-model="selectedDoctor"
            placeholder="选择医生"
            clearable
            style="width: 100%"
            @on-change="handleDoctorChange"
          >
            <Option v-for="doc in doctors" :key="doc.id" :value="doc.id">
              {{ doc.name }}
            </Option>
          </Select>
        </Col>
        <Col span="6">
          <Button type="primary" icon="md-refresh" :loading="isLoading" @click="refreshData">
            刷新数据
          </Button>
        </Col>
      </Row>
    </Card>

    <!-- 数据概览卡片 -->
    <Row :gutter="16" class="stat-cards">
      <Col span="6">
        <Card>
          <div class="stat-card">
            <div class="stat-icon">
              <Icon type="md-calendar" />
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ todayAppointments }}</div>
              <div class="stat-label">今日预约总数</div>
            </div>
          </div>
        </Card>
      </Col>
      <Col span="6">
        <Card>
          <div class="stat-card">
            <div class="stat-icon waiting">
              <Icon type="md-time" />
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ waitingAppointments }}</div>
              <div class="stat-label">待就诊人数</div>
            </div>
          </div>
        </Card>
      </Col>
      <Col span="6">
        <Card>
          <div class="stat-card">
            <div class="stat-icon completed">
              <Icon type="md-checkmark-circle" />
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ completedAppointments }}</div>
              <div class="stat-label">已就诊人数</div>
            </div>
          </div>
        </Card>
      </Col>
      <Col span="6">
        <Card>
          <div class="stat-card">
            <div class="stat-icon cancelled">
              <Icon type="md-close-circle" />
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ cancelledAppointments }}</div>
              <div class="stat-label">已取消预约</div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 图表区域 -->
    <Row :gutter="16" class="chart-row">
      <Col span="16">
        <Card>
          <div slot="title" class="card-title">
            <Icon type="md-trending-up" />
            <span>预约趋势</span>
          </div>
          <div class="chart-container">
            <div ref="appointmentTrendChart" style="height: 400px"></div>
          </div>
        </Card>
      </Col>
      <Col span="8">
        <Card>
          <div slot="title" class="card-title">
            <Icon type="md-pie" />
            <span>预约状态分布</span>
          </div>
          <div class="chart-container">
            <div ref="appointmentStatusChart" style="height: 400px"></div>
          </div>
        </Card>
      </Col>
    </Row>

    <Row :gutter="16" class="chart-row">
      <Col span="12">
        <Card>
          <div slot="title" class="card-title">
            <Icon type="md-pie" />
            <span>科室就诊量分布</span>
          </div>
          <div class="chart-container">
            <div ref="departmentPieChart" style="height: 400px"></div>
          </div>
        </Card>
      </Col>
      <Col span="12">
        <Card>
          <div slot="title" class="card-title">
            <Icon type="md-stats" />
            <span>科室就诊量对比</span>
          </div>
          <div class="chart-container">
            <div ref="departmentBarChart" style="height: 400px"></div>
          </div>
        </Card>
      </Col>
    </Row>

    <Row :gutter="16" class="chart-row">
      <Col span="24">
        <Card>
          <div slot="title" class="card-title">
            <Icon type="md-analytics" />
            <span>科室预约趋势</span>
          </div>
          <div class="chart-container">
            <div ref="departmentTrendChart" style="height: 400px"></div>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getRequest } from '@/libs/axios'
import { formatDate } from '@/utils/date'

export default {
  name: 'ResourceAnalysis',
  data() {
    return {
      // 筛选条件
      dateRange: [],
      selectedDepartment: '',
      selectedDoctor: '',
      isLoading: false,

      // 数据列表
      departments: [],
      doctors: [],

      // 统计数据
      todayAppointments: 0,
      waitingAppointments: 0,
      completedAppointments: 0,
      cancelledAppointments: 0,

      // 图表实例
      appointmentTrendChart: null,
      appointmentStatusChart: null,
      departmentPieChart: null,
      departmentBarChart: null,
      departmentTrendChart: null,

      // 日期选择器配置
      dateOptions: {
        shortcuts: [
          {
            text: '最近一周',
            value() {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              return [start, end]
            }
          },
          {
            text: '最近一个月',
            value() {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              return [start, end]
            }
          },
          {
            text: '最近三个月',
            value() {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              return [start, end]
            }
          }
        ]
      }
    }
  },
  methods: {
    handleDateChange(dates) {
      this.refreshData()
    },

    handleDepartmentChange(value) {
      this.loadDoctors(value)
      this.refreshData()
    },

    handleDoctorChange(value) {
      this.refreshData()
    },

    async loadDepartments() {
      try {
        const res = await getRequest('/hospitalSubject/getAll')
        if (res.success) {
          this.departments = res.result.map(item => ({
            id: item.id,
            name: item.subName
          }))
        }
      } catch (error) {
        this.$Message.error('加载科室列表失败：' + error.message)
      }
    },

    async loadDoctors(departmentId) {
      if (!departmentId) {
        this.doctors = []
        return
      }
      try {
        console.log('Loading doctors for department:', departmentId)
        const res = await getRequest('/doctor/getByPage', {
          pageNumber: 1,
          pageSize: 100,
          subjectId: departmentId
        })
        console.log('Doctor response:', res)
        if (res.success && res.result && res.result.records) {
          this.doctors = res.result.records.map(item => ({
            id: item.id,
            name: item.doctorName
          }))
          console.log('Mapped doctors:', this.doctors)
        } else {
          console.warn('Invalid doctor response:', res)
        }
      } catch (error) {
        console.error('Failed to load doctors:', error)
        this.$Message.error('加载医生列表失败：' + error.message)
      }
    },

    async refreshData() {
      this.isLoading = true
      try {
        const params = {
          startDate: this.dateRange[0] ? formatDate(this.dateRange[0], 'yyyy-MM-dd') : '',
          endDate: this.dateRange[1] ? formatDate(this.dateRange[1], 'yyyy-MM-dd') : '',
          departmentId: this.selectedDepartment,
          doctorId: this.selectedDoctor
        }

        const [statsRes, trendRes, statusRes, distributionRes, comparisonRes, departmentTrendRes] = await Promise.all([
          getRequest('/resource/stats', params),
          getRequest('/resource/trend', params),
          getRequest('/resource/status', params),
          getRequest('/resource/department', params),
          getRequest('/resource/department/comparison', params),
          getRequest('/resource/department/trend', params)
        ])

        if (statsRes.success) {
          const stats = statsRes.result || {}
          this.todayAppointments = stats.totalCount || 0
          this.waitingAppointments = stats.waitingCount || 0
          this.completedAppointments = stats.completedCount || 0
          this.cancelledAppointments = stats.cancelledCount || 0
        }

        if (trendRes.success && trendRes.result) {
          this.updateAppointmentTrendChart(trendRes.result)
        }

        if (statusRes.success && statusRes.result) {
          this.updateAppointmentStatusChart(statusRes.result)
        }

        // 更新科室分布图表
        if (distributionRes.success && distributionRes.result) {
          this.updateDepartmentDistributionChart(distributionRes.result)
        }

        // 更新科室对比图表
        if (comparisonRes.success && comparisonRes.result) {
          this.updateDepartmentComparisonChart(comparisonRes.result)
        }

        // 更新科室趋势图表
        if (departmentTrendRes.success && departmentTrendRes.result) {
          this.updateDepartmentTrendChart(departmentTrendRes.result)
        }
      } catch (error) {
        console.error('Failed to refresh data:', error)
        this.$Message.error('加载数据失败：' + error.message)
      } finally {
        this.isLoading = false
      }
    },

    updateAppointmentTrendChart(data) {
      this.appointmentTrendChart.setOption({
        xAxis: {
          type: 'time',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '预约数量'
        },
        series: [{
          name: '预约数量',
          type: 'line',
          smooth: true,
          data: data.map(item => [item.date, item.count])
        }]
      })
    },

    updateAppointmentStatusChart(data) {
      this.appointmentStatusChart.setOption({
        series: [{
          data: [
            { value: data.waiting, name: '待就诊' },
            { value: data.completed, name: '已就诊' },
            { value: data.cancelled, name: '已取消' }
          ]
        }]
      })
    },

    updateDepartmentDistributionChart(data) {
      // 更新科室分布饼图
      this.departmentPieChart.setOption({
        series: [{
          data: data.map(item => ({
            value: item.count,
            name: item.departmentName
          }))
        }]
      })
    },

    updateDepartmentComparisonChart(data) {
      // 更新科室对比柱状图
      this.departmentBarChart.setOption({
        xAxis: {
          data: data.map(item => item.departmentName)
        },
        series: [{
          data: data.map(item => item.count)
        }]
      })
    },

    updateDepartmentTrendChart(data) {
      // 处理趋势数据，按科室名称分组
      const departmentData = {}
      data.forEach(item => {
        if (!departmentData[item.departmentName]) {
          departmentData[item.departmentName] = []
        }
        departmentData[item.departmentName].push([item.date, item.count])
      })

      // 更新科室趋势图
      this.departmentTrendChart.setOption({
        legend: {
          data: Object.keys(departmentData)
        },
        series: Object.entries(departmentData).map(([name, data]) => ({
          name: name,
          type: 'line',
          smooth: true,
          data: data
        }))
      })
    },

    initCharts() {
      // 初始化预约趋势图表
      this.appointmentTrendChart = echarts.init(this.$refs.appointmentTrendChart)
      this.appointmentTrendChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          orient: 'horizontal',
          right: 10,
          bottom: 10
        },
        xAxis: {
          type: 'time',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '预约数量'
        },
        series: [{
          name: '预约数量',
          type: 'line',
          smooth: true,
          data: []
        }]
      })

      // 初始化预约状态分布图表
      this.appointmentStatusChart = echarts.init(this.$refs.appointmentStatusChart)
      this.appointmentStatusChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          right: 10,
          bottom: 10,
          textStyle: {
            fontSize: 12
          }
        },
        series: [{
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          data: []
        }]
      })

      // 初始化科室分布饼图
      this.departmentPieChart = echarts.init(this.$refs.departmentPieChart)
      this.departmentPieChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          right: 10,
          bottom: 10,
          textStyle: {
            fontSize: 12
          }
        },
        series: [{
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          data: []
        }]
      })

      // 初始化科室对比柱状图
      this.departmentBarChart = echarts.init(this.$refs.departmentBarChart)
      this.departmentBarChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          right: 10,
          bottom: 10
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '就诊量'
        },
        series: [{
          name: '就诊量',
          type: 'bar',
          data: []
        }]
      })

      // 初始化科室趋势图
      this.departmentTrendChart = echarts.init(this.$refs.departmentTrendChart)
      this.departmentTrendChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          orient: 'horizontal',
          right: 10,
          bottom: 10,
          textStyle: {
            fontSize: 12
          }
        },
        xAxis: {
          type: 'time',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '就诊量'
        },
        series: []
      })
    },

    handleResize() {
      this.appointmentTrendChart && this.appointmentTrendChart.resize()
      this.appointmentStatusChart && this.appointmentStatusChart.resize()
      this.departmentPieChart && this.departmentPieChart.resize()
      this.departmentBarChart && this.departmentBarChart.resize()
      this.departmentTrendChart && this.departmentTrendChart.resize()
    },

    disposeCharts() {
      this.appointmentTrendChart && this.appointmentTrendChart.dispose()
      this.appointmentStatusChart && this.appointmentStatusChart.dispose()
      this.departmentPieChart && this.departmentPieChart.dispose()
      this.departmentBarChart && this.departmentBarChart.dispose()
      this.departmentTrendChart && this.departmentTrendChart.dispose()
    }
  },
  mounted() {
    this.initCharts()
    this.loadDepartments()
    this.refreshData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.disposeCharts()
  }
}
</script>

<style lang="less" scoped>
.resource-analysis {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);

  .filter-card {
    margin-bottom: 20px;
  }

  .card-title {
    display: flex;
    align-items: center;
    
    .ivu-icon {
      margin-right: 8px;
      font-size: 16px;
    }
  }

  .stat-cards {
    margin-bottom: 20px;

    .stat-card {
      display: flex;
      align-items: center;
      padding: 20px;

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background-color: #2d8cf0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .ivu-icon {
          font-size: 24px;
          color: #fff;
        }

        &.waiting {
          background-color: #ff9900;
        }

        &.completed {
          background-color: #19be6b;
        }

        &.cancelled {
          background-color: #ed4014;
        }
      }

      .stat-content {
        flex: 1;

        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #17233d;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 14px;
          color: #808695;
        }
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;

    .chart-container {
      position: relative;
      width: 100%;
      height: 100%;
      padding: 8px;
    }
  }

  :deep(.ivu-card-head) {
    padding: 14px 16px;
    background-color: #f8f8f9;
  }

  :deep(.ivu-card-body) {
    padding: 16px;
  }
}
</style>
